﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using Ue.Infrastructure.Web.UI;
using Ue.Qcdz.Domain;
using Ue.Qcdz.Domain.Membership;
using Ue.Qcdz.Domain.Roles;

namespace Ue.Qcdz.UI.Controls.Membership
{
    public class UserActivation : SkinnedControl
    {
        #region Overrides of SkinnedControl

        private string skinFileName = "~/Themes/zh-cn/Skins/UserActivation.ascx";
        protected override string GetSkinFileName()
        {
            return skinFileName;
        }

        protected override void InitializeSkin(Control skin)
        {
            if (this.Page.Request["Id"] != null && this.Page.Request["key"] != null)
            {
                SetActivation(this.Page.Request["Id"], Page.Request["key"]);
            }
        }
        private void SetActivation(string userId, string key)
        {
            if (Ue.Framework.Security.DEncryptUtils.MD5EnCode(userId).Equals(key))
            {
                Guid uId = new Guid(userId);
                IUserRepository repository =
                Ue.Infrastructure.RepositoryFramework.RepositoryFactory.GetRepository<IUserRepository, User>();
                User user = repository.FindBy(uId);
                if (user.State == EntityState.Disable)
                {
                    if (user.CreateOn.AddDays(1) < DateTime.Now)
                    {
                        MessageWindow.RenderMessage("您的帐号已经过期，请在注册后24小时之内进行激活。如有问题请联系网站管理员！", "Login.aspx");
                    }
                    else
                    {
                        IRoleRepository rolerepository = Ue.Infrastructure.RepositoryFramework.RepositoryFactory.GetRepository<IRoleRepository, Role>();
                        Guid roleKey = new Guid("6137B3EE-976B-4749-AE9E-07B2292AF3CE");
                        user.ChangeStatus();
                        var role = new Role(roleKey);
                        var roles = new List<Role> { role };
                        repository[user.Key] = user;
                        rolerepository.AddInUserRole(roles, userId);
                        MessageWindow.RenderMessage("用户激活成功", "Login.aspx");
                    }
                }
                else
                {
                    MessageWindow.RenderMessage("用户不需要激活", "Login.aspx");
                }
               
            }
            else
            {
                MessageWindow.RenderMessage("请勿随便修改参数","Default.aspx");
            }
        }

        #endregion
    }
}
